package com.mcxx.modules.temporary.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.DictConstant;
import com.mcxx.convert.TmpApplyConvert;
import com.mcxx.modules.minimumliving.service.FiscalAbutmentService;
import com.mcxx.modules.temporary.service.TempSalvationApplyService;
import com.mcxx.modules.base.service.read.AreaReadService;
import com.mcxx.modules.base.service.read.BankMappingReadService;
import com.mcxx.modules.base.service.read.DictionaryReadService;
import com.mcxx.modules.base.service.read.RuleEngineReadService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.check.service.read.CheckReadService;
import com.mcxx.modules.miniSalvation.family.dto.BankAbutmentDTO;
import com.mcxx.modules.miniSalvation.family.dto.FamilyThreeMemberDTO;
import com.mcxx.modules.miniSalvation.family.dto.MemberCardRtnDTO;
import com.mcxx.modules.miniSalvation.family.entity.BankEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMainEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.service.read.*;
import com.mcxx.modules.miniSalvation.family.service.write.BankWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMainWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMemberWriteService;
import com.mcxx.modules.miniSalvation.order.dto.OrderInHouseDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderCertEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.BlacklistReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCertReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.InHouseWriteService;
import com.mcxx.modules.miniSalvation.salary.dto.MemberSalaryDTO;
import com.mcxx.modules.temporary.family.dto.TempFamilyDTO;
import com.mcxx.modules.temporary.family.dto.TempMemberCardRtnDTO;
import com.mcxx.modules.temporary.family.dto.TmpFamilyMemberDTO;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMainBackUpEntity;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMainEntity;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMemberEntity;
import com.mcxx.modules.temporary.family.service.read.TmpFamilyMainReadService;
import com.mcxx.modules.temporary.family.service.read.TmpFamilyMemberReadService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMainWriteService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMemberWriteService;
import com.mcxx.modules.temporary.order.dto.ApplicationDTO;
import com.mcxx.modules.temporary.order.dto.ApplyRtnDTO;
import com.mcxx.modules.temporary.order.dto.TmpOrderDTO;
import com.mcxx.modules.temporary.order.dto.TmpOrderStateVerifyDTO;
import com.mcxx.modules.temporary.order.entity.TmpOrderCertEntity;
import com.mcxx.modules.temporary.order.entity.TmpOrderEntity;
import com.mcxx.modules.temporary.order.service.read.TmpOrderCertReadService;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.modules.temporary.order.service.write.TmpOrderCertWriteService;
import com.mcxx.modules.temporary.order.service.write.TmpOrderWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.core.utils.UUIDUtils;
import com.yinhai.ta404.module.dict.entity.TaDictPo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;


@Service
@TaTransactional
public class TempSalvationApplyServiceImpl extends BaseService implements TempSalvationApplyService {
    @Autowired
    private FamilyMainWriteService familyMainWriteService;
    @Autowired
    private FamilyMemberWriteService familyMemberWriteService;
    @Autowired
    private TmpFamilyMainWriteService tmpFamilyMainWriteService;
    @Autowired
    private TmpFamilyMainReadService familyMainReadService;
    @Autowired
    private FamilyMainReadService minFamilyMainReadService;
    @Autowired
    private FamilyMemberReadService minFamilyMemberReadService;
    @Autowired
    private TmpOrderWriteService orderWriteService;
    @Autowired
    private TmpOrderReadService orderReadService;
    @Autowired
    private OrderReadService minOrderReadService;
    @Autowired
    private DictionaryReadService dictionaryReadService;
    @Autowired
    private  TmpFamilyMemberReadService tmpFamilyMemberReadService;
    @Autowired
    private  TmpFamilyMemberWriteService tmpFamilyMemberWriteService;
    @Autowired
    private  TmpFamilyMainReadService tmpFamilyMainReadService;
    @Autowired
    private BlacklistReadService blacklistReadService;
    @Autowired
    private TmpOrderCertReadService  orderCertReadService;
    @Value("${society.template.dir:bakhtml}")
    private String backUpDir;
    @Value("${society.template.tmpfilename:tmpbackup.html}")
    private String backUpFileName;
    @Autowired
    private FileService fileService;
    @Autowired
    private RuleEngineReadService ruleEngineReadService;
    @Autowired
    private InHouseWriteService inHouseWriteService;
    @Autowired
    private AreaReadService areaReadService;
    @Autowired
    private FamilyMemberHistoryReadService familyMemberHistoryReadService;
    @Autowired
    private FamilyThreeMemberReadService familyThreeMemberReadService;
    @Autowired
    private CheckReadService checkReadService;
    @Autowired
    private BankMappingReadService bankMappingReadService;
    @Autowired
    private FiscalAbutmentService fiscalAbutmentService;
    @Autowired
    private BankReadService bankReadService;
    @Autowired
    private BankWriteService bankWriteService;
    @Autowired
    private OrderCertReadService certReadService;
    @Autowired
    private TmpOrderCertWriteService orderCertWriteService;

    private final  String separator = System.getProperty("file.separator");

    @Override
    public BaseResult<ApplyRtnDTO> saveSalvationRequest(ApplicationDTO applyDto, UserAccountVo accountVo) throws BizException {

        if(!CommonUtil.invalidArgs(applyDto.getOrderId())){
            TmpOrderStateVerifyDTO orderState = orderReadService.getBizStateReportFile(applyDto.getOrderId());
            ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.ORDER_EDIT, orderState, accountVo);
        }


        List<TmpFamilyMemberEntity> memberLists = tmpFamilyMemberReadService.listByFamilyId(applyDto.getFamilyId());
        if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(memberLists)){

            tmpFamilyMemberWriteService.updateIsSaveByFamilyId(applyDto.getFamilyId());

            tmpFamilyMainWriteService.updateSaveMemberByFamilyId(applyDto.getFamilyId());
            List<String> list = new ArrayList<>();
            for(TmpFamilyMemberEntity memberList : memberLists){
                list.add(memberList.getIdcard());
            }
            List<String> names = blacklistReadService.cntByIdcards(list);
            if(CollectionUtils.isNotEmpty(names)){
                throw  new BizException("-1","当前家庭成员【" + String.join(",", names) + "】在黑名单中");
            }

            this.verifyApplyMaster(applyDto);
        }
        if(!CommonUtil.invalidArgs(applyDto.getOrderId())){


            this.cntFamilyMaster(applyDto.getFamilyId());

            this.verifyApplyMaster(applyDto);

            this.cntCompleteInfoNum(applyDto.getFamilyId());

            this.verifyTmpCert(applyDto.getOrderId(),applyDto.getFamilyId());
        }
        BaseResult<ApplyRtnDTO> baseResult = new BaseResult<>();


        Date applyDate = applyDto.getApplyDate();

        String applyMonth = DateUtil.formatDate(applyDate, "yyyyMM");
//        int saveTimes = orderReadService.countByIdCardAndReason(applyDto.getIdcard(),applyDto.getMainReason(),applyYear);







//            baseResult.setCode(FailureCode.ERR_20036.getCode());
//            baseResult.setMsg(FailureCode.ERR_20036.getMessage());



        int saveTimes = orderReadService.countByIdCardAndMonth(applyDto.getIdcard(), applyMonth);
        if (saveTimes > 0) {
            throw new BizException("-1","该救助对象所在家庭选的救助年月" + applyMonth + "已救助过，不能再次申请救助 ");
        }


        TmpFamilyMainEntity familyMainEntity = TmpApplyConvert.convertToFamilyMainEntity(applyDto, accountVo);
        TmpFamilyMemberEntity memberEntity = TmpApplyConvert.convertToFamilyMemberEntity(applyDto, accountVo);


        ApplyRtnDTO rtnDTO = tmpFamilyMainWriteService.addFamilyAndMember4Apply(familyMainEntity, memberEntity);


        applyDto.setFamilyId(rtnDTO.getFamilyId());
        applyDto.setMemberId(rtnDTO.getMemberId());
        TmpOrderEntity orderEntity = TmpApplyConvert.convertToOrderEntity(applyDto, accountVo);

        TmpFamilyMemberEntity masertInfo = tmpFamilyMemberReadService.getMasertInfo(rtnDTO.getFamilyId());
        if(masertInfo != null){
            orderEntity.setName(masertInfo.getName());
            orderEntity.setIdcard(masertInfo.getIdcard());
            orderEntity.setMemberId(masertInfo.getId());
        }

        if (StringUtils.isEmpty(applyDto.getOrderId())) {

            orderEntity.setId(IdUtil.simpleUUID());
            orderEntity.setState(Constant.BizStateTmp.SALVATION);
            orderEntity.setBizState(Constant.BizStateTmp.SALVATION);

            String userLevel = accountVo.getAreaLevel();

            if (Integer.parseInt(userLevel) <= 3) {

                orderEntity.setState(Constant.BizStateTmp.COUNTY_TODO_DOWN_ING);
                orderEntity.setBizState(Constant.BizStateTmp.COUNTY_TODO_DOWN_ING);
            }
            orderEntity.setField04(Constant.WOASTATE.UNPROCESSED);
            orderWriteService.addOrder(orderEntity);
        } else {
//            if(!CommonUtil.invalidArgs(applyDto.getOrderBizState())){
//                orderEntity.setBizState(applyDto.getOrderBizState());

//            if(!CommonUtil.invalidArgs(applyDto.getOrderState())){
//                orderEntity.setState(applyDto.getOrderState());


            orderWriteService.updateOrder(orderEntity);
        }


        tmpFamilyMemberWriteService.updateAreaCodeByFamilyId(applyDto.getAreaCode(), rtnDTO.getFamilyId());

        applyDto.setOrderId(orderEntity.getId());

        copyFamilyAndMemberDatum(applyDto,memberLists);


        applyDto.setAreaCode(accountVo.getAreaCode());
        generateBankInfo(applyDto);


        rtnDTO.setOrderId(orderEntity.getId());
        rtnDTO.setOrderBizState(orderEntity.getBizState());
        baseResult.setData(rtnDTO);

        return baseResult;
    }


    private void copyFamilyAndMemberDatum(ApplicationDTO applyDto, List<TmpFamilyMemberEntity> memberLists) {
        List<String> memberIdCards = memberLists.stream().map(TmpFamilyMemberEntity::getIdcard).collect(toList());

        OrderEntity orderEntity = minFamilyMainReadService.getOrderInfoByIdCard(applyDto.getApplyIdcard());
        List<OrderCertEntity> list = new ArrayList<>();
        List<Map<String, String>> memberIds = new ArrayList<>();
        if (null != orderEntity) {
            if (!memberIdCards.isEmpty())
                memberIds = minFamilyMainReadService.getMemberByIdCards(memberIdCards);

            list = certReadService.selectDatumByOrderIdAndFileType(orderEntity.getOrderId(), null, null);
        } else {

            orderEntity = minFamilyMainReadService.getLowerOrderInfoByIdCard(applyDto.getApplyIdcard());
            if (null != orderEntity) {
                if (!memberIdCards.isEmpty())
                    memberIds = minFamilyMainReadService.getLowerMemberByIdCards(memberIdCards);
                list = certReadService.selectDatumByOrderIdAndFileType(orderEntity.getOrderId(), null, null);
            }
        }

        Map<String, List<OrderCertEntity>> datumMap = list.stream().collect(Collectors.groupingBy(OrderCertEntity::getFileType));

        List<OrderCertEntity> houseDatum = datumMap.get(Constant.FileType.HOUSEHOLD_REGISTER);
        if (houseDatum != null && !houseDatum.isEmpty()) {
            OrderCertEntity certEntity = houseDatum.get(0);
            TmpOrderCertEntity tmpOrderEntity = new TmpOrderCertEntity();
            BeanUtils.copyProperties(certEntity, tmpOrderEntity);
            tmpOrderEntity.setId(Constant.getUUID());
            tmpOrderEntity.setAssociationTableId(applyDto.getFamilyId());
            tmpOrderEntity.setOrderId(applyDto.getOrderId());
            List<OrderCertEntity> tempCertList = certReadService.selectDatumByOrderIdAndFileType(applyDto.getOrderId(), Constant.FileType.HOUSEHOLD_REGISTER, 1);
            if (tempCertList.isEmpty())
                orderCertWriteService.insertIgnoreNull(tmpOrderEntity);
        }


        Map<String, List<TmpFamilyMemberEntity>> tempMemberMap = memberLists.stream().collect(Collectors.groupingBy(TmpFamilyMemberEntity::getIdcard));

        List<OrderCertEntity> memberDatums = datumMap.get(Constant.FileType.IDCARD);

        List<OrderCertEntity> tempCertList = certReadService.selectDatumByOrderIdAndFileType(applyDto.getOrderId(), Constant.FileType.IDCARD, 2);

        if (memberDatums != null) {
            for (Map<String, String> obj : memberIds) {
                for (OrderCertEntity cert : memberDatums) {
                    if (obj.get("memberId").equals(cert.getAssociationTableId())) {
                        TmpOrderCertEntity tmpOrderEntity = new TmpOrderCertEntity();
                        BeanUtils.copyProperties(cert, tmpOrderEntity);
                        tmpOrderEntity.setId(Constant.getUUID());
                        TmpFamilyMemberEntity temp = tempMemberMap.get(obj.get("idCard")).get(0);
                        tmpOrderEntity.setAssociationTableId(temp.getId());
                        tmpOrderEntity.setOrderId(applyDto.getOrderId());
                        if (tempCertList.isEmpty())
                            orderCertWriteService.insertIgnoreNull(tmpOrderEntity);
                    }
                }
            }
        }
    }


    private void generateBankInfo(ApplicationDTO applyDto) {
        List<BankEntity> rst = bankReadService.getBankByApplyIdCardAndBizType(applyDto.getApplyIdcard(), Constant.BusinessCode.LINSHI);
        BankEntity bankEntity = null;
        if (rst.size() == 0) {
            bankEntity = BankEntity.convertBankInfoFromApplyInfo(applyDto);
            bankEntity.setAgentBankPhone(applyDto.getPhone());
            bankEntity.setMasterPhone(applyDto.getPhone());
            bankWriteService.insertIgnoreNull(bankEntity);
        }
        if (rst.size() == 1) {
            bankEntity = rst.get(0);
            bankEntity.setMasterAccount(applyDto.getApplyAccount());
            bankEntity.setMasterBankCode(applyDto.getApplyBankCode());
            bankEntity.setMasterSubsideProps(applyDto.getApplySubsideProps());
            bankEntity.setAgentBankPhone(applyDto.getPhone());
            bankEntity.setMasterPhone(applyDto.getPhone());
            bankWriteService.updateIgnoreNull(bankEntity);
        }
        if (rst.size() > 1) {
            List<BankEntity> noDel = new ArrayList<>();
            for (BankEntity obj : rst) {
                if (obj.getFamilyId().equals(applyDto.getFamilyId()) && obj.getMemberId().equals(applyDto.getMemberId())) {
                    noDel.add(obj);
                }
            }

            List<BankEntity> subList = rst.stream()
                    .filter(item -> !noDel.stream().map(BankEntity::getId)
                            .collect(Collectors.toList()).contains(item.getId()))
                    .collect(Collectors.toList());

            for (BankEntity obj : subList) {
                bankWriteService.deleteBankInfo(obj.getId());
            }
            if (noDel.size() > 1) {
                List<BankEntity> sortList = noDel.stream().sorted(Comparator.comparingLong(e->DateUtil.str2Timestamp(e.getCreateTime()).getTime()))
                        .collect(toList());
                BankEntity last = sortList.get(sortList.size()-1);
                sortList.remove(last);
                for (BankEntity obj : sortList) {
                    bankWriteService.deleteBankInfo(obj.getId());
                }
            }

        }
    }

    @Override
    public void modifyTmpOrder(TmpOrderEntity tmpOrderEntity) throws BizException {
        orderWriteService.updateOrder(tmpOrderEntity);
    }

    @Override
    public BaseResult<TempFamilyDTO> queryStateByIdCard(String idcard,UserAccountVo accountVo,String channel) {
        BaseResult<TempFamilyDTO> baseResult = new BaseResult<>();

        int rst = blacklistReadService.cntByIdcard(idcard);
        if(rst > 0){
            throw new BizException(FailureCode.ERR_10033);
        }

        MemberCardRtnDTO memberCardRtn = familyMemberHistoryReadService.queryMemberHistoryByCardId(idcard);
        if(null != memberCardRtn){

            this.dealFinishedOrder(memberCardRtn);
        }

        MemberCardRtnDTO lowerMemberCardRtn = familyMemberHistoryReadService.queryLowerMemberHistoryByCardId(idcard);
        if(null != lowerMemberCardRtn){

            this.dealFinishedOrder(lowerMemberCardRtn);
        }

        TempFamilyDTO familyDTO = familyMainReadService.getByMemberIdCard(idcard);


        if (familyDTO == null && channel!=null && channel.equals(Constant.CHANNEL.WXAPP)) {
            OrderEntity otherOrder = minOrderReadService.getLatestFinishedOrder(idcard);
            if (otherOrder != null) {
                familyDTO = new TempFamilyDTO();
                familyDTO.setBusinessCode(otherOrder.getBusinessType());
                familyDTO.setStandType(otherOrder.getStandType());
                baseResult.setData(familyDTO);
            }
            return baseResult;
        }


        if (familyDTO == null) {

            familyDTO = searchDibaoBusiness(idcard,memberCardRtn,channel);

            if(null == familyDTO){
                familyDTO = searchLowerBusiness(idcard,lowerMemberCardRtn);

                if(null == familyDTO){
                    return baseResult;
                }
            }
        }else{

            List<TmpOrderDTO> list = orderReadService.listTodoByFamilyId(familyDTO.getFamilyId());
            for (TmpOrderDTO orderDTO : list) {
                TaDictPo operTypeDict = dictionaryReadService.getCodeCache(DictConstant.OPERATION_TYPE, orderDTO.getType());
                TaDictPo stateDict = dictionaryReadService.getCodeCache(DictConstant.BIZSTATETEMP, orderDTO.getState());
                baseResult.setCode("-1");
                baseResult.setMsg("该人员正在"+orderDTO.getCounty()+orderDTO.getStreet()+
                        orderDTO.getCommunity()+"【"+orderDTO.getName()+"】家庭中办理临时救助"+
                        operTypeDict.getLabel() + "，状态" + stateDict.getLabel());
                return baseResult;
            }
        }

        OrderEntity otherOrder =  minOrderReadService.getLatestFinishedOrder(idcard);
        if (otherOrder != null) {
            familyDTO.setBusinessCode(otherOrder.getBusinessType());
            familyDTO.setStandType(otherOrder.getStandType());
        }

        int a = areaReadService.getCountByAreaCode(familyDTO.getAreaCode(),accountVo.getAreaCode());
        if (a == 0){
            familyDTO.setAreaCode("");
        }

        baseResult.setData(familyDTO);
        return baseResult;
    }


    public TempFamilyDTO searchDibaoBusiness(String idcard,MemberCardRtnDTO memberCardRtn,String channel){

        String familyId = minFamilyMainReadService.getFamilyIdByMemberIdCard(idcard);
        if (StringUtils.isEmpty(familyId)) {

            return null;
        }

        if(null != memberCardRtn && familyId.equals(memberCardRtn.getFamilyId()) &&
                (Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberCardRtn.getMemberState())||Constant.PeopleState.MARRIED.equals(memberCardRtn.getMemberState()))){

            String newFamilyId = IdUtil.simpleUUID();
            tmpFamilyMainWriteService.copyFromSplittingSource(familyId,newFamilyId,idcard);
            tmpFamilyMemberWriteService.copyFromSplittingSource(familyId,newFamilyId,memberCardRtn.getMemberState());
        } else {


            String newFamilyId = IdUtil.simpleUUID();
            tmpFamilyMainWriteService.copyFromOtherSource(familyId,newFamilyId);
            tmpFamilyMemberWriteService.copyFromOtherSource(familyId,newFamilyId);
        }

        TempFamilyDTO familyDTO = familyMainReadService.getByMemberIdCard(idcard);
        if (channel!=null && channel.equals(Constant.CHANNEL.WXAPP)) {
            familyMainWriteService.deleteFamilyMainById(memberCardRtn.getFamilyId());
            familyMemberWriteService.deleteFamilyMemberById(memberCardRtn.getFamilyId());
        }
        return familyDTO;
    }

    public TempFamilyDTO searchLowerBusiness(String idcard,MemberCardRtnDTO memberCardRtn){

        String familyId = minFamilyMainReadService.getLowerFamilyIdByMemberIdCard(idcard);
        if (StringUtils.isEmpty(familyId)) {

            return null;
        }

        if(null != memberCardRtn && familyId.equals(memberCardRtn.getFamilyId()) &&
                (Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberCardRtn.getMemberState())||Constant.PeopleState.MARRIED.equals(memberCardRtn.getMemberState()))){

            String newFamilyId = IdUtil.simpleUUID();
            tmpFamilyMainWriteService.copyFromLowerSplitSource(familyId,newFamilyId);
            tmpFamilyMemberWriteService.copyFromLowerSplitSource(familyId,newFamilyId,memberCardRtn.getMemberState());
        }else{

            String newFamilyId = IdUtil.simpleUUID();
            tmpFamilyMainWriteService.copyFromLowerSource(familyId,newFamilyId);
            tmpFamilyMemberWriteService.copyFromLowerSource(familyId,newFamilyId);
        }

        TempFamilyDTO familyDTO = familyMainReadService.getByMemberIdCard(idcard);
        return familyDTO;
    }

    private void dealFinishedOrder(MemberCardRtnDTO memberCardRtn){

        String memberState = memberCardRtn.getMemberState();
        String orderType = memberCardRtn.getOrderType();

        if(null == memberState || null == orderType){
            throw new BizException(FailureCode.ERR_10047);
        }


        if(Constant.PeopleState.DEAD.equals(memberState)){
            throw new BizException(FailureCode.ERR_10037.getCode(), packagingCardMsgNoSalvation(memberCardRtn));
        }
    }

    private String packagingCardMsgNoSalvation(MemberCardRtnDTO memberCardRtn){

        TaDictPo businessTypeDict = dictionaryReadService.getCodeCache(DictConstant.BUSINESS_TYPE, memberCardRtn.getBusinessType());

        TaDictPo orderTypeDict = dictionaryReadService.getCodeCache(DictConstant.OPERATION_TYPE, memberCardRtn.getOrderType());

        TaDictPo orderBizStateDict = dictionaryReadService.getCodeCache(DictConstant.BIZSTATE, memberCardRtn.getOrderState());

        TaDictPo memberStateDict = dictionaryReadService.getCodeCache(DictConstant.SURVIVAL_STATUS, memberCardRtn.getMemberState());

        StringBuffer msg = new StringBuffer();
        msg.append("该人员在 ")
                .append(memberCardRtn.getCountyCode())
                .append(memberCardRtn.getStreetCode())
                .append(memberCardRtn.getAreaCode())
                .append("【")
                .append(memberCardRtn.getMasterMemberName())
                .append("】家庭中办理 ")
                .append(businessTypeDict.getLabel())
                .append(orderTypeDict.getLabel())
                .append(",")
                .append(orderBizStateDict.getLabel())
                .append(",该人员状态:");

        if(Constant.SuspendFlag.SUSPEND_STATE.equals(memberCardRtn.getSuspendFlag())){
            msg.append("暂停");
        }else{
            msg.append(memberStateDict.getLabel());
        }
        return msg.toString();
    }


    @Override
    public BaseResult<Integer> countByIdCardAndReason(String idcard, String mainReason, String year,UserAccountVo accountVo) {
        BaseResult<Integer> baseResult = new BaseResult<>();


        int count = orderReadService.countsByIdCardAndReason(idcard, mainReason, year);
        baseResult.setData(count);
        if (count == 0) {
            return baseResult;
        }


        int upperLimit = orderReadService.getSalvationLimit(accountVo.getAreaCode().substring(0, 6), Constant.BusinessCode.LINSHI, "01");



//            baseResult.setCode(FailureCode.ERR_20036.getCode());
//            baseResult.setMsg(FailureCode.ERR_20036.getMsg());





//            baseResult.setCode(FailureCode.ERR_20035.getCode());
//            baseResult.setMsg(FailureCode.ERR_20035.getMsg());




        if (count >= upperLimit) {
            baseResult.setCode(FailureCode.ERR_20035.getCode());
            TaDictPo tempPovertyFactorsStateDict = dictionaryReadService.getCodeCache(DictConstant.TempPovertyFactors, mainReason);
            baseResult.setMsg("该申请人一年内由于同一【"+tempPovertyFactorsStateDict.getLabel() +"】原因申请临时救助次数超过了2次，是否确认继续申请救助");
            return baseResult;
        }

        return baseResult;
    }


    @Override
    public List<TempMemberCardRtnDTO> queryMemberByCardId(String idcard){
         List<TempMemberCardRtnDTO> list = tmpFamilyMemberReadService.queryMemberByCardId(idcard);
         for(TempMemberCardRtnDTO cardRtnDTO:list){
             if(StringUtils.isNotEmpty(cardRtnDTO.getStartMonth()) && cardRtnDTO.getStartMonth().length()>7){
                 cardRtnDTO.setStartMonth(cardRtnDTO.getStartMonth().substring(0,7));
             }
         }
         return list;
    }


    @Override
    public BaseResult<Map> queryMemberStateByIdCard(String idcard) {
        BaseResult<Map> baseResult = new BaseResult<>();

        int rst = blacklistReadService.cntByIdcard(idcard);
        if(rst > 0){
            throw new BizException(FailureCode.ERR_10033);
        }
        Map<String,String> resultMap = new HashMap<>();

        FamilyThreeMemberDTO familyThreeMemberDTO  = familyThreeMemberReadService.queryMemberByCardId(idcard);
        if(!CommonUtil.invalidArgs(familyThreeMemberDTO)){
            resultMap.put("ruralObjectType", familyThreeMemberDTO.getRuralObjectType());
        }

        TmpFamilyMemberEntity memberEntity = tmpFamilyMemberReadService.getByIdCard(idcard);
        if (CommonUtil.invalidArgs(memberEntity)) {
            baseResult.setData(resultMap);
            return baseResult;
        }


        List<TmpOrderDTO> list = orderReadService.listTodoByFamilyId(memberEntity.getFamilyId());
        for (TmpOrderDTO orderDTO : list) {
            TaDictPo operTypeDict = dictionaryReadService.getCodeCache(DictConstant.OPERATION_TYPE, orderDTO.getType());
            TaDictPo stateDict = dictionaryReadService.getCodeCache(DictConstant.BIZSTATETEMP, orderDTO.getState());
            baseResult.setCode("-1");
            baseResult.setMsg("该人员正在"+orderDTO.getCounty()+orderDTO.getStreet()+
                    orderDTO.getCommunity()+"【"+orderDTO.getName()+"】家庭中办理临时救助"+
                    operTypeDict.getLabel() + "，状态" + stateDict.getLabel());
            return baseResult;
        }


        resultMap.put("familyId", memberEntity.getFamilyId());
        resultMap.put("memberId", memberEntity.getId());
        resultMap.put("name", memberEntity.getName());
        resultMap.put("nation", memberEntity.getNation());
        resultMap.put("familyRelation", memberEntity.getFamilyRelation());
        baseResult.setData(resultMap);

        return baseResult;
    }

    public void cntFamilyMaster(String familyId){
        int cntMaster  = tmpFamilyMemberReadService.cntFamilyMaster(familyId);
        if(cntMaster > 1){
            throw new BizException(FailureCode.ERR_10080);
        }
        if(cntMaster == 0){
            throw new BizException(FailureCode.ERR_10081);
        }
    }

    public void verifyApplyMaster(ApplicationDTO applyDto){
        String masterIdCard = tmpFamilyMemberReadService.selectMasterIdcard(applyDto.getFamilyId());

        if(StringUtils.isNotEmpty(masterIdCard) && masterIdCard.equals(applyDto.getApplyIdcard())&&!Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
            throw new BizException(FailureCode.ERR_10081);
        }

        if(Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
            if(StringUtils.isNotEmpty(masterIdCard) && !masterIdCard.equals(applyDto.getApplyIdcard())){
                throw new BizException(FailureCode.ERR_20004);
            }
        }
    }

    public void cntCompleteInfoNum(String familyId){
        String rst = tmpFamilyMemberReadService.cntCompleteInfoNum(familyId);
        if(!CommonUtil.invalidArgs(rst)){
            throw new BizException(FailureCode.ERR_20067);
        }else{
            List<TmpFamilyMemberEntity> tmpFamilyMemberEntities = tmpFamilyMemberReadService.listByFamilyId(familyId);
            for(TmpFamilyMemberEntity tmpFamilyMemberEntity:tmpFamilyMemberEntities){
                if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getCensusType())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】户籍类别信息未完善");
                }else if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getCensusPlace())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】户籍地址信息未完善");
                }else if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getEducation())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】文化程度信息未完善");
                }else if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getIsLocalPlace())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】是否本地户籍未完善");
                }else if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getHealthState())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】健康状况未完善");
                }else if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getWorkPower())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】劳动能力未完善");
                }else if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getFamilyRelation())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】与户主关系未完善");
                }else if(CommonUtil.invalidArgs(tmpFamilyMemberEntity.getMarryState())){
                    throw new BizException("-1", "成员【" + tmpFamilyMemberEntity.getName() + "】婚姻状况为空");
                }

            }
        }
    }

    public void verifyTmpCert(String orderId,String familyId){

        Map<String, Long> mustCertMap = orderCertReadService.selectTmpMustCert(orderId, familyId);
        if(mustCertMap.containsKey("familyRegister")&&mustCertMap.get("familyRegister")<1){
            throw new BizException("-1", "当前家庭没有上传【户口本】资料，请上传！");
        }

//        if(mustCertMap.containsKey("checkAuthorizationNum") && mustCertMap.get("checkAuthorizationNum") <= 0){


        if(mustCertMap.containsKey("tmpApplication")&&mustCertMap.get("tmpApplication")<1){
            throw new BizException("-1", "当前家庭没有上传【临时救助申请书】资料，请上传！");
        }

        List<String> idcards = orderCertReadService.selectTmpMemberNoCert(orderId, familyId);
        if(CollectionUtils.isNotEmpty(idcards)){
            throw  new BizException("-1","当前成员【" + String.join(",", idcards) + "】没有上传身份证，请先上传身份证");
        }
    }

    public void verifyBackUpHtml(String orderId){
        String objId = orderReadService.selectObjIdById(orderId);
        if(CommonUtil.invalidArgs(objId)){
            throw new BizException("-1", "未完成信息备份，不能进行该流程");
        }
    }

    public String backupHtml(String orderId,String familyId) {


        this.cntFamilyMaster(familyId);

        this.cntCompleteInfoNum(familyId);

        this.verifyTmpCert(orderId,familyId);


        InputStream htmlInputStream = this.getClass().getResourceAsStream("/"+backUpDir+"/"+backUpFileName);


        TmpFamilyMainBackUpEntity mainEntity = familyMainReadService.selectBackUpInfo(orderId);

        List<TmpFamilyMemberEntity> memberList = tmpFamilyMemberReadService.listByFamilyId(familyId);


        TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,mainEntity.getRelation());
        mainEntity.setRelation(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.CENSUS_TYPE,mainEntity.getCensusType());
        mainEntity.setCensusType(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.TemporaryType,mainEntity.getObjectType());
        mainEntity.setTempSaveType(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.TempPovertyFactors,mainEntity.getMainReason());
        mainEntity.setMainReason(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.TEMPOBJECTTYPE,mainEntity.getObjectType());
        mainEntity.setObjectType(taDictPo.getLabel());

        for(TmpFamilyMemberEntity memberEntity:memberList){

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,memberEntity.getFamilyRelation());
            memberEntity.setFamilyRelation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.EDUCATION_LEVEL,memberEntity.getEducation());
            memberEntity.setEducation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.HEALTH,memberEntity.getHealthState());
            memberEntity.setHealthState(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.WORK_POWER,memberEntity.getWorkPower());
            memberEntity.setWorkPower(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.Employment_Status,memberEntity.getWorkState());
            memberEntity.setWorkState(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.CENSUS_TYPE,memberEntity.getCensusType());
            memberEntity.setCensusType(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.NATION,memberEntity.getNation());
            memberEntity.setNation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.SERIOUS_DISEASE,memberEntity.getSeriousDisease());
            memberEntity.setSeriousDisease(taDictPo.getLabel());

            memberEntity.setSex(StringUtils.isBlank(memberEntity.getSex())?"":dictionaryReadService.getCodeCache(DictConstant.SEX,memberEntity.getSex()).getLabel());

            memberEntity.setDisabilityLevel(StringUtils.isBlank(memberEntity.getDisabilityLevel())?"":dictionaryReadService.getCodeCache(DictConstant.DISABLED_LEVEL,memberEntity.getDisabilityLevel()).getLabel());

            memberEntity.setDisabilityType(StringUtils.isBlank(memberEntity.getDisabilityType())?"":dictionaryReadService.getCodeCache(DictConstant.DISABLE_TYPE,memberEntity.getDisabilityType()).getLabel());

            memberEntity.setSelfcareLevel(StringUtils.isBlank(memberEntity.getSelfcareLevel())?"":dictionaryReadService.getCodeCache(DictConstant.SelfCareAbility,memberEntity.getSelfcareLevel()).getLabel());
        }

        String uuid = UUIDUtils.getUUID();
        File tmpFile = new File(System.getProperty("java.io.tmpdir")+separator +uuid+".html");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(htmlInputStream));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile)));
            String line = "";
            Gson gson = new GsonBuilder().serializeNulls().create();
            while((line=reader.readLine())!=null){
                writer.write(line);
                writer.newLine();
                if(line.indexOf("<script>")>0){

                    StringBuffer familyBuffer =  new StringBuffer();

                    familyBuffer.append("var familyInfo = ");
                    familyBuffer.append(gson.toJson(mainEntity));
                    writer.write(familyBuffer.toString());
                    writer.newLine();

                    writer.write("var memberDatas=");
                    writer.write(gson.toJson(memberList));
                    writer.newLine();
                }
            }
            writer.close();
            reader.close();

            FileInputStream input = new FileInputStream(tmpFile);
            String objectKey = fileService.upload(input,tmpFile.getName());

            TmpOrderEntity orderEntity = new TmpOrderEntity();
            orderEntity.setId(orderId);
            orderEntity.setFileObjId(objectKey);
            orderWriteService.updateOrder(orderEntity);

            tmpFile.delete();
            return objectKey;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1","备份发生异常");
        }
    }


    @Override
    public ApplyRtnDTO tempSaveInHouse(ApplicationDTO applyDto, UserAccountVo accountVo) throws BizException {

        this.isCanTempSaveInHouse(applyDto, accountVo);


        BaseResult<ApplyRtnDTO> result = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        result.getData().setOrderInhouseId(inHouseId);


        return result.getData();
    }

    @Override
    public ApplyRtnDTO completeInHouse(ApplicationDTO applyDto, UserAccountVo accountVo) {

        this.isCanCompleteInHouse(applyDto, accountVo);


        this.verifyOrderInHouse(applyDto);


        BaseResult<ApplyRtnDTO> result = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        result.getData().setOrderInhouseId(inHouseId);


        return result.getData();
    }


    public void isCanTempSaveInHouse(ApplicationDTO applyDto, UserAccountVo accountVo){


        TmpOrderStateVerifyDTO tmpOrderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());


        ruleEngineReadService.getTempBizStateRuleThrow(Constant.OrderBizStateType.START_TOWN_IN_HOUSE, tmpOrderStateVerifyDTO, accountVo);


        applyDto.setOrderBizState(tmpOrderStateVerifyDTO.getNextBizState());
    }


    public void isCanCompleteInHouse(ApplicationDTO applyDto, UserAccountVo userAccountVo){


        TmpOrderStateVerifyDTO tmpOrderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());

        tmpOrderStateVerifyDTO.setNextCondition("1");


        ruleEngineReadService.getTempBizStateRuleThrow(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE, tmpOrderStateVerifyDTO, userAccountVo);


        applyDto.setOrderBizState(tmpOrderStateVerifyDTO.getNextBizState());
//        applyDto.setOrderState(tmpOrderStateVerifyDTO.getNextState());
    }


    public void verifyOrderInHouse(ApplicationDTO applyDto){

        if(CommonUtil.invalidArgs(CommonUtil.invalidArgs(applyDto.getCheckPeople()) || CommonUtil.invalidArgs(applyDto.getCheckDate())
                || CommonUtil.invalidArgs(applyDto.getCheckContent()))){
            throw new BizException(FailureCode.ERR_20014);
        }


        if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(applyDto.getInhouseCertIdList())){

            return;
        }

        int rst = orderCertReadService.cntInhouseCertNum(applyDto.getOrderId(), applyDto.getOrderInhouseId());
        if(rst <= 0){
            throw new BizException("-1", "当前家庭没有上传【入户调查辅证材料】，请上传！");
        }
    }



    public String saveOrderInHouse(ApplicationDTO applyDto, UserAccountVo userAccountVo) {

        if(CommonUtil.invalidArgs(applyDto.getCheckPeople()) || CommonUtil.invalidArgs(applyDto.getCheckDate())
                || CommonUtil.invalidArgs(applyDto.getCheckContent())){

            return null;
        }


        OrderInHouseDTO inHouseDTO = TmpApplyConvert.convertToInhouseEntity(applyDto);


        if(CommonUtil.invalidArgs(inHouseDTO.getId())){
            inHouseWriteService.addTempInHouse(inHouseDTO, applyDto.getInhouseCertIdList(), userAccountVo);
        }else{
            inHouseWriteService.updateTempById(inHouseDTO, applyDto.getInhouseCertIdList(), userAccountVo);
        }
        return inHouseDTO.getId();
    }

    @Override
    public void verifyExpireCheck(String orderId){
        int count = checkReadService.selectExpireRecord(orderId);

        if(count<1){
            throw new BizException(FailureCode.ERR_20088);
        }
    }
    @Override
    public Map<String, String> gainBankInfo(BankAbutmentDTO dto, UserAccountVo userAccountVo) {
        Map<String, String> map = new HashMap<>();
        if(StringUtils.isEmpty(dto.getSsssidcardnum())){
            throw new BizException("-1","身份证号码不能为空");
        }
        if(StringUtils.isEmpty(dto.getSsssobjectname())){
            throw new BizException("-1","姓名不能为空");
        }
        if(StringUtils.isEmpty(dto.getBankcode())){
            throw new BizException("-1","开户银行不能为空");
        }
        if(StringUtils.isEmpty(dto.getAccouttype())){
            throw new BizException("-1","账号类型不能为空");
        }

        if(Constant.FundCapitalType.SOCIAL_SECURITY.equals(dto.getAccouttype())){
            dto.setAccouttype("0");
        }else{
            dto.setAccouttype("1");
        }


        String tenantIdStr = areaReadService.getTenantIdRela(userAccountVo.getOrgId().substring(0,6)+"000000");
        dto.setTenantId(tenantIdStr);

        String bankCode = bankMappingReadService.getFinanceByRescue(dto.getBankcode());
        dto.setBankcode(bankCode);
        dto.setDatasources("01");

        String result = fiscalAbutmentService.fiscalAbutmentInfo(dto);

        if(!StringUtils.isEmpty(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");

            if("-1".equals(code)){
                throw new BizException("-1","当前补贴对象未绑定银行帐号");
            }else{
                String data = jsonObject.getString("data");
                JSONObject jsonData = JSONObject.parseArray(data).getJSONObject(0);
                String accountnum = jsonData.getString("accountnum");
                map.put("accountnum",accountnum);
            }
        }
        return map;
    }


    public void isCanEditOrder(String orderId, UserAccountVo accountVo){

        TmpOrderStateVerifyDTO orderState = orderReadService.getBizStateReportFile(orderId);
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.ORDER_EDIT, orderState, accountVo);
    }

    @Override
    public void delete(TmpFamilyMemberDTO dto, UserAccountVo accountVo){
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        tmpFamilyMemberWriteService.delete(dto,accountVo);
    }

    @Override
    public void addFamilyMember(TmpFamilyMemberDTO dto,UserAccountVo accountVo){
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        tmpFamilyMemberWriteService.addFamilyMember(dto,accountVo);
    }

    @Override
    public void  updateFamilyMember(TmpFamilyMemberDTO dto,UserAccountVo accountVo)  {
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        tmpFamilyMemberWriteService.updateFamilyMember(dto,accountVo);
    }

    @Override
    public void changeMemberApply(String familyId, String orderId, Map<String,String> relationshipMap,UserAccountVo accountVo){
        this.isCanEditOrder(orderId,accountVo);
        tmpFamilyMemberWriteService.changeMemberApply(familyId,orderId,relationshipMap);
    }


    @Override
    public BaseResult<TempFamilyDTO> getPersonInfoByIdCard(String idCard, UserAccountVo curUser, String channel) {

        BaseResult<TempFamilyDTO> result = new BaseResult<>();

        int rst = blacklistReadService.cntByIdcard(idCard);
        if(rst > 0){
            throw new BizException(FailureCode.ERR_10033);
        }

        MemberCardRtnDTO memberCardRtn = familyMemberHistoryReadService.queryMemberHistoryByCardId(idCard);
        if(null != memberCardRtn){

            this.dealFinishedOrder(memberCardRtn);
        }

        MemberCardRtnDTO lowerMemberCardRtn = familyMemberHistoryReadService.queryLowerMemberHistoryByCardId(idCard);
        if(null != lowerMemberCardRtn){

            this.dealFinishedOrder(lowerMemberCardRtn);
        }

        TempFamilyDTO familyDTO = null;

        List<TempFamilyDTO> familyDTOs = familyMainReadService.getByMemberByApplyIdCard(idCard);
        if (familyDTOs.size() > 1) {

            OrderEntity tempOrder = orderReadService.selectInfoByIdCard(idCard);
            if (null == tempOrder) {
                tmpFamilyMainWriteService.deleteFamilyMainByIdCard(idCard);
                tmpFamilyMemberWriteService.deleteFamilyMemberByIdCard(idCard);
                familyDTOs.clear();
            } else {
                tmpFamilyMainWriteService.deleteFamilyMainByIdCardAndNoHasFamilyId(idCard, tempOrder.getFamilyId());
                tmpFamilyMemberWriteService.deleteFamilyMemberByIdCardAndNoHasFamilyId(idCard, tempOrder.getFamilyId());
                Optional<TempFamilyDTO> memberOption  = familyDTOs.stream().filter(o-> o.getFamilyId().equals(tempOrder.getFamilyId())).findFirst();
                if (memberOption.isPresent())
                    familyDTO = memberOption.get();
            }
        }
        if (familyDTOs.size() == 1)
            familyDTO = familyDTOs.get(0);

        if (familyDTOs.isEmpty()) {

            familyDTO = searchDibaoBusiness(idCard,memberCardRtn,channel);

            if(null == familyDTO){
                familyDTO = searchLowerBusiness(idCard,lowerMemberCardRtn);

                if(null == familyDTO){
                    return result;
                }
            }
        }else{

            TempFamilyDTO familyDTO1 = updateMinAndPovertyBusiness(idCard, memberCardRtn);

            if (null == familyDTO1) {
                TempFamilyDTO familyDTO2 = updateLowerBusiness(idCard,lowerMemberCardRtn);
                if (null != familyDTO2) {
                    familyDTO = familyDTO2;
                }
            } else {
                familyDTO = familyDTO1;
            }

            List<TmpOrderDTO> list = orderReadService.listTodoByApplyIdCard(idCard);

            List<TmpOrderDTO> list1 = orderReadService.listTodoByFamilyId(familyDTO.getFamilyId());
            list.addAll(list1);
            for (TmpOrderDTO orderDTO : list) {
                TaDictPo operTypeDict = dictionaryReadService.getCodeCache(DictConstant.OPERATION_TYPE, orderDTO.getType());
                TaDictPo stateDict = dictionaryReadService.getCodeCache(DictConstant.BIZSTATETEMP, orderDTO.getState());
                result.setCode("-1");
                result.setMsg("该人员正在"+orderDTO.getCounty()+orderDTO.getStreet()+
                        orderDTO.getCommunity()+"【"+orderDTO.getName()+"】家庭中办理临时救助"+
                        operTypeDict.getLabel() + "，状态" + stateDict.getLabel());
                return result;
            }
        }

        OrderEntity otherOrder =  minOrderReadService.getLatestFinishedOrder(idCard);
        if (otherOrder != null) {
            familyDTO.setBusinessCode(otherOrder.getBusinessType());
            familyDTO.setStandType(otherOrder.getStandType());
        }

        int a = areaReadService.getCountByAreaCode(familyDTO.getAreaCode(),curUser.getAreaCode());
        if (a == 0){
            familyDTO.setAreaCode("");
        }

        result.setData(familyDTO);
        return result;
    }


    private TempFamilyDTO updateLowerBusiness(String idCard, MemberCardRtnDTO memberCardRtn) {

        String familyId = minFamilyMainReadService.getLowerFamilyIdByMemberIdCard(idCard);
        if (!StringUtils.isEmpty(familyId)) {

            if (null != memberCardRtn && familyId.equals(memberCardRtn.getFamilyId())) {

                List<FamilyMemberEntity> memberList = minFamilyMemberReadService.listLowerByFamilyId(familyId);

                List<FamilyMemberEntity> deadList = memberList.stream().filter(o -> Constant.PeopleState.DEAD.equals(o.getState())).collect(Collectors.toList());

                List<FamilyMemberEntity> marryList = memberList.stream().filter(o -> Constant.PeopleState.MARRIED.equals(o.getState())).collect(Collectors.toList());
                List<FamilyMemberEntity> moveList = memberList.stream().filter(o -> Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(o.getState())).collect(Collectors.toList());
                List<FamilyMemberEntity> normalList = memberList.stream().filter(
                        o -> !Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(o.getState())
                                && !Constant.PeopleState.MARRIED.equals(o.getState())
                                && !Constant.PeopleState.DEAD.equals(o.getState())).collect(Collectors.toList());

                dealWithDeadMember(deadList);
                dealWithNewMember(memberList, marryList, familyId, Constant.BusinessCode.DISHOURU,idCard);
                dealWithNewMember(memberList, moveList, familyId, Constant.BusinessCode.DISHOURU,idCard);

                dealWithNormalMember(normalList, familyId, Constant.BusinessCode.DISHOURU, idCard);
            }
        }

        TempFamilyDTO familyDTO = familyMainReadService.getByMemberIdCard(idCard);
        return familyDTO;
    }


    private TempFamilyDTO updateMinAndPovertyBusiness(String idCard, MemberCardRtnDTO memberCardRtn) {

        String familyId = minFamilyMainReadService.getFamilyIdByMemberIdCard(idCard);
        if (StringUtils.isEmpty(familyId)) {

            return null;
        }

        if (null != memberCardRtn && familyId.equals(memberCardRtn.getFamilyId())) {

            List<FamilyMemberEntity> memberList = minFamilyMemberReadService.listByFamilyId(familyId);

            List<FamilyMemberEntity> deadList = memberList.stream().filter(o -> Constant.PeopleState.DEAD.equals(o.getState())).collect(Collectors.toList());

            List<FamilyMemberEntity> marryList = memberList.stream().filter(o -> Constant.PeopleState.MARRIED.equals(o.getState())).collect(Collectors.toList());
            List<FamilyMemberEntity> moveList = memberList.stream().filter(o -> Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(o.getState())).collect(Collectors.toList());
            List<FamilyMemberEntity> normalList = memberList.stream().filter(
                    o -> !Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(o.getState())
                    && !Constant.PeopleState.MARRIED.equals(o.getState())
                    && !Constant.PeopleState.DEAD.equals(o.getState())).collect(Collectors.toList());

            dealWithDeadMember(deadList);
            dealWithNewMember(memberList, marryList, familyId, null,idCard);
            dealWithNewMember(memberList, moveList, familyId, null,idCard);

            dealWithNormalMember(normalList, familyId, null, idCard);
        }

        TempFamilyDTO familyDTO = familyMainReadService.getByMemberIdCard(idCard);
        return familyDTO;
    }


    private void dealWithNormalMember(List<FamilyMemberEntity> normalList,
                                      String familyId,
                                      String type,
                                      String idCard) {
        List<String> idCards = normalList.stream().map(FamilyMemberEntity::getIdcard).collect(toList());
        if (!idCards.isEmpty()) {

            List<TmpFamilyMemberEntity> tempMembers = tmpFamilyMemberReadService.getTempMemberByIdCards(idCards);

            if (!tempMembers.isEmpty()) {

                FamilyMainEntity minFamily = null;
                if (null != type) {

                    minFamily = minFamilyMainReadService.getLowerFamilyById(familyId);
                } else {
                    minFamily = minFamilyMainReadService.getById(familyId);
                }

                TmpFamilyMainEntity tempFamily = new TmpFamilyMainEntity();
                BeanUtils.copyProperties(minFamily, tempFamily);
                String temFamilyId = tempMembers.get(0).getFamilyId();
                tempFamily.setId(temFamilyId);
                tempFamily.setFamilyNumber(normalList.size());
                tmpFamilyMainWriteService.updateFamily(tempFamily);


                for (FamilyMemberEntity obj : normalList) {
                    for (TmpFamilyMemberEntity tmpObj : tempMembers) {
                        if (obj.getIdcard().equals(tmpObj.getIdcard())) {
                            String temMemberId = tmpObj.getId();
                            BeanUtils.copyProperties(obj,tmpObj);
                            tmpObj.setId(temMemberId);
                            tmpObj.setFamilyId(temFamilyId);
                            tmpFamilyMemberWriteService.updateFamilyMember(tmpObj);
                        }
                    }
                }

                List<String> tempMemberIdCards = tempMembers.stream().map(TmpFamilyMemberEntity::getIdcard).collect(toList());

                List<String> diffCards =
                        idCards.stream().filter(item -> !new ArrayList<>(tempMemberIdCards).contains(item)).collect(Collectors.toList());
                for (FamilyMemberEntity obj : normalList) {
                    for (String card : diffCards) {
                        if (card.equals(obj.getIdcard())) {
                            TmpFamilyMemberEntity tmpMember = new TmpFamilyMemberEntity();
                            BeanUtils.copyProperties(obj,tmpMember);
                            tmpFamilyMemberWriteService.addFamilyMember(tmpMember);
                        }
                    }
                }


                List<String> normalTempMemberIdCards = tmpFamilyMemberReadService.getTempMemberByFamilyId(temFamilyId);

                List<String> diffCards1 =
                        normalTempMemberIdCards.stream().filter(item -> !new ArrayList<>(tempMemberIdCards).contains(item)).collect(Collectors.toList());
                if (!diffCards1.isEmpty()) {
                    for (String card : diffCards1) {
                        tmpFamilyMemberWriteService.deleteFamilyMemberByIdCard(card);
                    }
                }
            }
        }
    }


    private void dealWithNewMember(List<FamilyMemberEntity> memberList,
                                   List<FamilyMemberEntity> marryAndMoveList,
                                   String familyId,
                                   String type,
                                   String idCard) {
        List<String> idCards = marryAndMoveList.stream().map(FamilyMemberEntity::getIdcard).collect(toList());
        if (!idCards.isEmpty()) {

            List<TmpFamilyMemberEntity> tempMembers = tmpFamilyMemberReadService.getTempMemberByIdCards(idCards);


            FamilyMainEntity minFamily = null;
            if (null != type) {

                minFamily = minFamilyMainReadService.getLowerFamilyById(familyId);
            } else {
                minFamily = minFamilyMainReadService.getById(familyId);
            }


            for (FamilyMemberEntity obj : marryAndMoveList) {
                for (TmpFamilyMemberEntity tmpObj : tempMembers) {
                    if (obj.getIdcard().equals(tmpObj.getIdcard())) {

                        TmpFamilyMainEntity mmFamily = tmpFamilyMainReadService.getFamilyByIdCard(obj.getIdcard(), tmpObj.getFamilyId());
                        TmpFamilyMainEntity tempFamily = new TmpFamilyMainEntity();
                        if (null == mmFamily) {
                            minFamily.setId(Constant.getUUID());
                            BeanUtils.copyProperties(minFamily, tempFamily);
                            tempFamily.setMainReason(Constant.DomesticRelation.ONESELF);
                            tempFamily.setIdcard(obj.getIdcard());
                            tempFamily.setName(obj.getName());
                            tempFamily.setFamilyNumber(1);
                            tmpFamilyMainWriteService.addFamily(tempFamily);

                            tmpObj.setFamilyId(tempFamily.getId());
                            tmpObj.setFamilyRelation(Constant.DomesticRelation.ONESELF);
                            tmpFamilyMemberWriteService.updateFamilyMember(tmpObj);

                            tmpFamilyMainWriteService.deleteFamilyMainByIdCardAndNoHasFamilyId(obj.getIdcard(), tmpObj.getFamilyId());
                        }
                    }
                }
            }
        }
    }


    private void dealWithDeadMember(List<FamilyMemberEntity> deadList) {
        List<String> idCards = deadList.stream().map(FamilyMemberEntity::getIdcard).collect(toList());

        if (!idCards.isEmpty()) {
            tmpFamilyMemberWriteService.deleteMemberByIdCards(idCards);

            List<String> familyIds = tmpFamilyMemberReadService.getFamilyInfoByMemberIdCards(idCards);
            if (!familyIds.isEmpty())
                tmpFamilyMainWriteService.updateTempFamilyInfo(familyIds);
        }
    }

}
